#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models
from web import utils


def add():
    host_list=models.Hosts.objects.all()
    for host in host_list:
        cmd1='grep -r server_name /usr/local/webserver/nginx/conf/vhosts/*.conf'
        cmd2='grep -r server_name /usr/local/nginx/conf/vhost/*.conf'
        try:
            result=utils.ssh_cmd(host.ip_addr,host.port,cmd1)
            if result==[]:
                result = utils.ssh_cmd(host.ip_addr, host.port, cmd2)
        except Exception as e:
            print("%s connect failed!" % (host.ip_addr))
            result=[]
        for line in result:
            line=line.strip().strip(';').split()
            conf=line[0].strip(':')
            domain_list=line[2:]
            #domain=domain.split('/')[-1]
            #domain='.'.join(domain.split('.')[:-1])
            for domain in domain_list:
                if domain !='_':
                    try:
                        resultobj=models.Domain.objects.get(name=domain,host=host,conf=conf)
                    except Exception as e:
                        resultobj=None
                    if resultobj is None:
                        domainobj=models.Domain(name=domain,host=host,conf=conf)
                        domainobj.save()




def delete():
    models.Domain.objects.all().delete()


if __name__=='__main__':
    delete()
    add()

